<template>
  <div class="chat-view__input">
    <!-- 导航栏 -->
    <van-nav-bar title="极速问诊" left-text="" left-arrow @click-left="onClickLeft" class="chat-view__input__nav" />
    <!-- 面包屑导航 -->
    <el-breadcrumb class="mian" :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }" class="el-breadcrumb-item">描述病情</el-breadcrumb-item>
      <el-breadcrumb-item class="el-breadcrumb-item">匹配医生</el-breadcrumb-item>
      <el-breadcrumb-item class="el-breadcrumb-item"> 开始咨询</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 服务保障 -->
    <div class="box">
      <h2 class="h2">服务保障</h2>
      <div>
        <div>·专业医生</div>
        <div>·实时认证</div>
        <div>多轮沟通</div>
        <div>·超时退款</div>
      </div>
    </div>

    <!-- 风险告知及患者知情同意书 -->
    <div class="box1">
      <p>
        请您仔细阅读<a>《风险告知及患者知情同意书》</a>，如非复诊，我们仅提供医疗咨询服务。继续操作表示您知悉并同意上述告知内容。
      </p>
    </div>

    <!-- 聊天框 -->
    <div class="chat-view">
      <div class="chat-view__container" ref="containerRef">
        <!-- 循环渲染消息列表 -->
        <template v-for="item in messgeList" :key="item.id">
          <!-- robot -->
          <div class="chat-view-robot" v-if="item.type === 'robot'">
            <div class="chat-view-robot__avatar">
              <img class="img"
                src="https://img2.baidu.com/it/u=3357111167,2193179217&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1732122000&t=9e534edda3e8858d0f4d55e73cf9d18c" />
            </div>
            <div class="chat-view-robot__content">
              <div class="chat-view-robot__name"></div>
              <!-- 机器消息 -->
              <div class="chat-view-robot__msgBox">
                <div class="chat-view-robot__message" v-if="item.msg.text || item.msg.imgUrl || item.msg.voiceUrl">
                  <span class="text" v-if="item.msg.text">{{ item.msg.text }}</span>
                  <img class="img" :src="item.msg.imgUrl" alt="" v-if="item.msg.imgUrl" />
                </div>
              </div>
            </div>
          </div>
          <!-- 用户 -->
          <div class="chat-view-user" v-if="item.type === 'user'">
            <div class="chat-view-user__content">
              <div class="chat-view-user__name">{{ user.name }}</div>
              <div class="chat-view-user__msgBox">
                <div class="chat-view-user__message">
                  <span v-if="item.msg.text">{{ item.msg.text }}</span>
                  <img class="imgurl" :src="item.msg.imgUrl" alt="" v-if="item.msg.imgUrl" />
                 
                </div>
              </div>
            </div>
            <div class="chat-view-user__avatar">
              <img class="img"
                src="https://img1.baidu.com/it/u=2919297617,2404150031&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800"
                alt="" />
            </div>
          </div>
        </template>
      </div>
      <div class="chat-view-footer">
        <div class="chat-view-footer__keyword" v-if="kewwordList.length > 0">
          <KeywordList :list="kewwordList" @clickItem="clickItem" :keyword="inputValue" />
        </div>
        <div class="chat-view-footer__inputBox">
          <input class="input" @keydown.enter="onPressEnter" placeholder="请用5-500字描述具体症状" ref="inputRef"
            v-model="inputValue" enterkeyhint="send" />
            <input type="file" @change="handleFileChange" accept="image/*" style="display: none;" ref="fileInputRef" />
          <t-button @click="chooseFile" style="margin-left: 8px; height: 30px; font-size: 12px;background-color: cadetblue;">发送图片</t-button>
          <t-button class="button" :disabled="inputValue.trim().length <= 0 && !file" @click="sendMsg"
            style="color: aliceblue;">发送</t-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';
import KeywordList from '@/views/ChatView/components/KeywordList.vue';
import { v4 as uuidv4 } from 'uuid';
import { mockMessageList, type Message, user, robot, rotbotReply } from './config/index';
import { KEY_WORDSLIST } from './config/constant';
import { ArrowRight } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();
// 设置页面标题
document.title = '聊天';
// 创建一个ref，用于存储聊天框的DOM元素
const containerRef = ref<HTMLDivElement | null>(null);
// 创建一个ref，用于存储输入框的DOM元素
const inputRef = ref<HTMLInputElement>();
// 创建一个ref，用于存储输入框的值
const inputValue = ref('');
// 创建一个ref，用于存储消息列表
const messgeList = ref<Array<Message>>(mockMessageList);
// 创建一个ref，用于存储选中的文件
const file = ref<File | null>(null);
// 创建一个ref，用于存储文件选择器
const fileInputRef = ref<HTMLInputElement | null>(null);
// 创建一个ref，用于存储用户输入的消息
const inputMessage = ref('');

// 初始化滚动条位置
const init = () => {
  const dom = containerRef.value as HTMLDivElement;
  if (dom) {
    setTimeout(() => {
      dom.scrollTo(0, dom.scrollHeight + 100);
    }, 0);
  }
};

// 用户发言
const userSpeak = (item: string, file: File | null = null) => {
  const userMsg: Message = {
    id: uuidv4(),
    type: 'user',
    msg: {
      text: item,
      imgUrl: file ? URL.createObjectURL(file) : undefined,
       voiceUrl: file ? URL.createObjectURL(file) : undefined
    }
  };
  messgeList.value.push(userMsg);
  // 机器人回复
  robotSpeak(item);
};

// 机器人发言
const robotSpeak = (item: string) => {
  const mesInfo = rotbotReply(item);
  messgeList.value.push(mesInfo);
  init();
};

// 点击关键词
const clickItem = (item: string) => {
  inputValue.value = '';
  userSpeak(item);
};

// 发送消息
const sendMsg = () => {
  if (inputValue.value.trim().length > 0) {
    userSpeak(inputValue.value);
    inputValue.value = '';
    inputRef.value?.blur();
  } else if (file.value) {
    userSpeak('', file.value);
    file.value = null;
  }
};

// 按下回车键
const onPressEnter = () => {
  sendMsg();
};

// 计算关键词列表
const kewwordList = computed(() => {
  return KEY_WORDSLIST.filter((item) => item.includes(inputValue.value) && inputValue.value.trim());
});

// 返回上一级
const onClickLeft = () => {
  router.push('/layout/seekmedical');
};

// 选择文件
const chooseFile = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
};

// 处理文件选择
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    file.value = target.files[0];
  }
};
// const sendMessage = async () => {
//   const response = await fetch('/api/ai-reply', {
//     method: 'POST',
//     headers: { 'Content-Type': 'application/json' },
//     body: JSON.stringify({ message: inputMessage.value })
//   });
//   const data = await response.json();
//   msgList.push({ content: data.reply, type: '0' }); // AI回复
//   msgList.push({ content: inputMessage.value, type: '1' }); // 用户消息
//   inputMessage.value = ''; // 清空输入框
//   scrollToBottom();
// };
</script>

<style lang="less">
.chat-view__input {
  width: 100%;
  height: 100%;
  .chat-view__input__nav {
    width: 100%;
    height: 7%;
  }
  .mian{
    width: 300px;
    font-size: 0.3rem;
  }
}
*{
  // background:#f5f4f4;
  color:#000
}
.chat-view {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 60%;
  background-color: #fff;
  &__container {
    flex: 1;
    padding: 20px 12px;
    overflow-y: scroll;
  }
}

.chat-view-robot {
  display: flex;

  &__component {
    border-radius: 9px;
    width: calc(100% - 28px);
    background-color: #fff;
  }

  &__avatar {
    margin-right: 8px;
    width: 40px;
    height: 40px;
    border-radius: 50%;

    .img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }

  &__content {
    flex: 1;
    width: 100%;
  }

  &__name {
    margin-bottom: 2px;
    line-height: 16px;
    font-size: 10px;
    color: rgba(0, 0, 0, 0.6);
  }

  &__msgBox {
    display: flex;
    width: 100%;
    margin-bottom: 16px;
  }

  &__message {
    display: flex;
    flex-direction: column;
    padding: 12px;
    background-color: #fff;
    max-width: calc(100% - 52px);
    border-radius: 0 12px 12px 12px;

    .text {
      font-size: 14px;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.9);
    }

    .img {
      margin-top: 12px;
      width: 100%;
    }
  }
}

.chat-view-user {
  margin-bottom: 16px;
  display: flex;

  &__avatar {
    margin-left: 8px;
    width: 40px;
    height: 40px;
    border-radius: 50%;

    .img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }

  &__content {
    flex: 1;
  }

  &__name {
    text-align: right;
    margin-bottom: 2px;
    line-height: 16px;
    font-size: 10px;
    color: rgba(0, 0, 0, 0.6);
  }

  &__msgBox {
    display: flex;
    flex-direction: row-reverse;
    width: 100%;
  }

  &__message {
    font-size: 14px;
    line-height: 22px;
    color: rgba(0, 0, 0, 0.9);
    padding: 12px;
    background-color: #d9e1ff;
    max-width: calc(100% - 52px);
    border-radius: 12px 0 12px 12px;
  }
}

.chat-view-footer {
width: 100%;
height: 2rem;
// width: 100%;
// height: 2rem;


  &__inputBox {
    background-color: #fff;
    padding: 12px;
    display: flex;
    align-items: center;
    height: 3.5rem;
    margin-top: -4rem;
    

    .input {
      box-sizing: border-box;
      flex: 1;
      height: 0.7rem;
      font-size: 14px;
      border-radius: 5px;
      outline: none;
      border: 1px solid #dcdcdcff;
      background-color: #f3f3f3ff;
    }

    .button {
      display: flex;
      display: inline-block;
      width: 50pc;
      height: 30px;
      line-height: 30px;
    margin-left: 10px;
      color: #fff;
      background-color: #b5cbed;
      // border-radius: 40px;
    }
  }

  &__keyword {
    position: absolute;
    bottom: 88px;
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;
    border-bottom: 0.5px solid #e7e7e7ff;
  }
}
.mian{
  width: 100%;
  height: 1rem;
  text-align: center;
  line-height: 1rem;
  font-size: 0.4rem;
  color: #fff;

  margin-left: 1rem;
}
.el-breadcrumb-item{
  margin-right: 1rem;
}
.box{
  width: 90%;
  height: 1.7rem;
  // text-align: center;
  // line-height: 1rem;
  // font-size: 0.4rem;
  margin-left: 5%;
  margin-top: 0.5rem;
  background: #f4f4f4;
  border-radius: .2rem;
  .h2{
    display: inline-block;
    margin-left: .625rem;
    margin-top:.2rem ;
    margin-bottom: .2rem;
  }
  p{
    margin-left: 0.3rem;
  }
  div{
    color:#ccc;
    float: left;
    margin-left: 0.2rem;
    margin-right: 0.2rem;
  }
}
.box1{
  width: 90%;
  height: 1.7rem;
  // text-align: center;
  // line-height: 1rem;
  // font-size: 0.4rem;
  margin-left: 5%;
  background: #efecec   !important;
  z-index: 9999;
  border-radius: .2rem;
margin-top: 0.5rem;
p{
  display: inline-block;
  background: #efecec;
  margin-top: 0.3rem;
  font-size: .3.5rem;
  color: #fff;
}
a{
  color:rgb(84, 84, 186);
   background: #efecec;
}
}
.imgurl{
  width: 30vw;
  height: 10vh;
}
.chat-view-footer__inputBox{
  width: 100%;
  height: 2rem;
  background: #e8eaed;
  position: fixed;
  top: 112%;
}
</style>